//
//  LeverageTradeViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/10/29.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "LeverageTradeViewController.h"
#import "MenuLeverageTradeView.h"
#import "LeverageTradeHeaderView.h"
#import "LeverageTradeView.h"
#import "TradeListRecordView.h"
#import "LeverageTradeModel.h"
#import "SocketRocketUtility.h"
#import "GGOrderListViewController.h"
#import "WK_StockChartViewController.h"


@interface LeverageTradeViewController ()

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIScrollView * scrollView;

@property(nonatomic, strong)LeverageTradeHeaderView * headerView;
@property(nonatomic, strong)LeverageTradeView *  tradeView;

@property(nonatomic, strong)TradeListRecordView * tradeListRecordView;

@property(nonatomic, weak)MenuLeverageTradeView * popView;

@property(nonatomic, assign)LeverageTradeViewType Type;
@property(nonatomic, strong)NSString * order_sn;

@property (nonatomic, strong) NSTimer * orderTimer;

@end

@implementation LeverageTradeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setProperty];
    [self createUI];
    [self performSelector:@selector(OpenWebScocket) withObject:nil afterDelay:3];
    
}


-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWebSocketdidReceiveMessageNote object:nil];
//    [self stopTimer];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    
    HomeBaseModel * Hmodel = [HomeBaseModel sharedHomeBaseModel];
    if (Hmodel.isNeedRemoveDataSource) {
        Hmodel.isNeedRemoveDataSource=NO;
        [self.tradeView removeLeverageTradeButtonListDataSource];
    }
    
    self.headerView.BTC.text=[NSString stringWithFormat:@"可用%@",Hmodel.selectedModel.base_symbol];
    self.headerView.USDT.text=[NSString stringWithFormat:@"可用%@",Hmodel.selectedModel.quote_symbol];

    [self OpenWebScocket];
    
    [self relayOutHeaderData];
    
    [self GetExLeverorderGetOrder];
//    [self setUpTimer];
    
    [self performSelector:@selector(Http_leverassets_currency) withObject:nil afterDelay:2];
    
}

-(void)OpenWebScocket{
    HomeBaseModel * Hmodel = [HomeBaseModel sharedHomeBaseModel];
    [LeverageTradeViewController openSocket:Hmodel.selectedModel];
}

#pragma mark-(void)openSocket:(HomeBaseTabCellModel *)homeBaseModel{
+(void)openSocket:(HomeBaseTabCellModel *)homeBaseModel{
    
    if (homeBaseModel) {
        if (!homeBaseModel.symbol) {
            return;
        }
        SocketRocketUtility * SK =[SocketRocketUtility instance];
        if (SK.socketReadyState != 1) {
            [SK SRWebSocketOpenWithURLString:WEBSOCKET_API_1];
        }
        NSString * args1 = [NSString stringWithFormat:@"depth.L20.%@",homeBaseModel.symbol];
        NSData *data1= [NSJSONSerialization dataWithJSONObject:@{
                                                                 @"cmd": @"sub",
                                                                 @"args": args1
                                                                 } options:NSJSONWritingPrettyPrinted error:nil];
        [SK sendData:data1];
        
        NSString * args2 = [NSString stringWithFormat:@"ticker.%@",homeBaseModel.symbol];
        NSData *data2= [NSJSONSerialization dataWithJSONObject:@{
                                                                 @"cmd": @"sub",
                                                                 @"args":args2
                                                                 } options:NSJSONWritingPrettyPrinted error:nil];
        [SK sendData:data2];
        
    }
}

+(void)dismissSocket:(HomeBaseTabCellModel *)homeBaseModel{
    if (homeBaseModel) {
        if (!homeBaseModel.symbol) {
            return;
        }
        SocketRocketUtility * SK =[SocketRocketUtility instance];
        NSString * args1 = [NSString stringWithFormat:@"depth.L20.%@",homeBaseModel.symbol];
        NSData *data1= [NSJSONSerialization dataWithJSONObject:@{
                                                                 @"cmd": @"unsub",
                                                                 @"args": args1
                                                                 } options:NSJSONWritingPrettyPrinted error:nil];
        [SK sendData:data1];
        
        NSString * args2 = [NSString stringWithFormat:@"ticker.%@",homeBaseModel.symbol];
        NSData *data2= [NSJSONSerialization dataWithJSONObject:@{
                                                                 @"cmd": @"unsub",          @"args": args2} options:NSJSONWritingPrettyPrinted error:nil];
        
        [SK sendData:data2];
    }
}

#pragma mark-刷新s头部数据
-(void)relayOutHeaderData{
    
    HomeBaseModel * Hmodel =[HomeBaseModel sharedHomeBaseModel];
    
    if (!Hmodel.selectedModel) {
        
        if (Hmodel.USDT.count>0) {
            Hmodel.selectedModel = Hmodel.USDT[0];
        }
    }
    if (Hmodel.selectedModel) {
        _headerView.title.text = [NSString stringWithFormat:@"%@/%@",Hmodel.selectedModel.base_symbol,Hmodel.selectedModel.quote_symbol];
        self.headerView.BTC.text=[NSString stringWithFormat:@"可用%@",Hmodel.selectedModel.base_symbol];
        self.headerView.USDT.text=[NSString stringWithFormat:@"可用%@",Hmodel.selectedModel.quote_symbol];

    }
    
}

#pragma mark-刷新数据

- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
//    NSString * message = note.object;
//    NSLog(@"-----收到服务端发送过来的消息--------%@",message);
    LeverageTradeModel * LTModel = [LeverageTradeModel sharedLeverageTradeModel];
    _tradeView.dataSource=LTModel;
    [self relayOutHeaderData];
    [self relayOutPopView];
}

#pragma mark-Header两个金额请求
-(void)Http_leverassets_currency{
    NSString * token = [LoginModel GetValue:DL_token];
    if (token.length<1) {
        return;
    }
    HomeBaseModel * Hmodel =[HomeBaseModel sharedHomeBaseModel];
    if (Hmodel.selectedModel.base_currency_id.length>0) {
        [self loadData_currency_ID:Hmodel.selectedModel.quote_currency_id andType:1];
    }
    if (Hmodel.selectedModel.quote_currency_id.length>0) {
        [self loadData_currency_ID:Hmodel.selectedModel.base_currency_id andType:2];
    }
}

#pragma mark-
-(void)loadData_currency_ID:(NSString *)ID andType:(NSInteger)type{

    __weak __typeof(self)wself = self;
    
    NSString * URL = [NSString stringWithFormat:@"%@leverassets/currency",DEFAULTSEVERBASEURL];
    NSString * sID = [NSString stringWithFormat:@"%@",ID];
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:@{@"currency_id":sID} SuccessBlock:^(id  _Nonnull responseObject) {
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSDictionary * dicc = dic[@"data"];
            NSString * available = [NSString stringWithFormat:@"%@",dicc[@"available"]];
            if (type == 1) {
                wself.headerView.USDTLab.text=available;
            }else if (type == 2){
                wself.headerView.BTCLab.text=available;

            }
        }
    } FailureBlock:^(id  _Nonnull error) {
    }];
}


-(void)setProperty{
    
    self.view.backgroundColor=RGB(255, 255, 255);
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
}

#pragma mark-KLine
-(void)GoToK_Line{
//
    HomeBaseModel * HB = [HomeBaseModel sharedHomeBaseModel];
    
    NSString * URL = [NSString stringWithFormat:@"%@/#/kline?counterparty=%@&base_symbol=%@&baseId=%@&quote_symbol=%@&quoteId=%@&pairId=%@",BASEURL_H5,HB.selectedModel.symbol,HB.selectedModel.base_symbol,HB.selectedModel.base_currency_id,HB.selectedModel.quote_symbol,HB.selectedModel.quote_currency_id,HB.selectedModel.pair_id];
    
    WK_StockChartViewController * VC = [[WK_StockChartViewController alloc]init];
    
//    K_LineWebViewController * VC = [[K_LineWebViewController alloc]init];
//    VC.url = URL;
//    VC.title=@"K_Line";
    
    [self.navigationController pushViewController:VC animated:YES];
    
}

-(void)createUI{
    WS(weakSelf);
    _scrollView = [[UIScrollView alloc]init];
    _scrollView.backgroundColor= [UIColor whiteColor];
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.view);
    }];
    [_scrollView setContentSize:CGSizeMake(G_SCREENWIDTH, G_SCREENHEIGHT*2)];
    
    LeverageTradeHeaderView *headerView = [[LeverageTradeHeaderView alloc]init];
    [_scrollView addSubview:headerView];
    headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, 160);

    _headerView = headerView;
    headerView.leftBtnBlock = ^{
        
        [weakSelf openMenu];
        
    };
    
    headerView.rightBtnBlock = ^{
        
        [weakSelf GoToK_Line];
        
    };
 
    LeverageTradeView *  tradeView = [[LeverageTradeView alloc]init];
    [_scrollView addSubview:tradeView];
    tradeView.frame=CGRectMake(0, 160, G_SCREENWIDTH, 400);
    _tradeView=tradeView;
    
    tradeView.block = ^(LeverageTradeViewType Type) {
        NSString * token = [LoginModel GetValue:DL_token];
        
        if (token.length>0) {
            weakSelf.Type=Type;
            if (Type == LeverageTradeViewType_Buy) {
                [weakSelf openAlert:[NSString stringWithFormat:@"确认买入%@个%@？",weakSelf.tradeView.textField_Num.text,weakSelf.tradeView.lab_base_symbol.text] andTag:10002];
            }else{
                [weakSelf openAlert:[NSString stringWithFormat:@"确认卖出%@个%@？",weakSelf.tradeView.textField_Num.text,weakSelf.tradeView.lab_base_symbol.text] andTag:10002];
            }
            
        }else{
            [weakSelf openAlert:@"请先登录" andTag:10001];
        }
    };
    
    TradeListRecordView * tradeListRecordView=[[TradeListRecordView alloc]init];
    [_scrollView addSubview:tradeListRecordView];
    tradeListRecordView.frame=CGRectMake(0, 560, G_SCREENWIDTH, 400);
    _tradeListRecordView=tradeListRecordView;
    _tradeListRecordView.allOrderBlock = ^{
        
        NSString * token = [LoginModel GetValue:DL_token];
        if (token.length>0) {
            GGOrderListViewController * VC = [[GGOrderListViewController alloc]init];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }else{
            [weakSelf openAlert:@"请先登录" andTag:10001];
        }
    };
    
    _tradeListRecordView.actionBlock = ^(NSInteger status, LTOrderCellModel * _Nonnull dataSource) {
        weakSelf.order_sn = dataSource.order_sn;
        //取消订单
        if (status == 1) {
            [weakSelf openAlert:@"确定撤单?" andTag:10003];
        //平仓
        }else if (status == 2){
            [weakSelf openAlert:@"确定平仓?" andTag:10004];
        }
    };
    
    _tradeListRecordView.refreshBlock = ^{
        [weakSelf GetExLeverorderGetOrder];
    };
    
    LeverageTradeModel * model = [LeverageTradeModel sharedLeverageTradeModel];
    tradeListRecordView.dataSource = model.orderModel;
    
    CGFloat HHHH = G_SCREENHEIGHT;
    if (G_SCREENHEIGHT<(560+400)) {
        HHHH = (560+400);
    }
    [_scrollView setContentSize:CGSizeMake(G_SCREENWIDTH, HHHH+1)];


    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.view  addGestureRecognizer:singleTapGesture];
    
}

#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
}


//
-(void)openAlert:(NSString *)title andTag:(NSInteger)tag{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:title delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate=self;
    alert.tag = tag;
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 10001) {
        if (buttonIndex == 1) { //确认
            LoginTool * LT = [LoginTool sharedLoginTool];
            LT.isGoToLogin=YES;
            self.tabBarController.selectedIndex = 3;
        }
    }else if (alertView.tag == 10002){
        if (buttonIndex == 1) { //确认
            [self LeverageTradeBuyOrSale:_Type];
        }
    }else if (alertView.tag == 10003){//撤单
        if (buttonIndex == 1) { //确认
            [self Http_leverorder_cancelorder:self.order_sn];
        }
    }else if (alertView.tag == 10004){//平仓
        if (buttonIndex == 1) { //确认
            [self Http_leverposition_close:self.order_sn];
        }
    }
}

#pragma mark-
-(void)LeverageTradeBuyOrSale:(LeverageTradeViewType )Type{
    
    HomeBaseModel * Hmodel =[HomeBaseModel sharedHomeBaseModel];
    
    NSString * order_type;//@1:限价买单；@2：限价卖单；
    if (Type==LeverageTradeViewType_Buy) {
        order_type=@"1";
    }else{
        order_type=@"2";
    }
    NSString * pair_id = [NSString stringWithFormat:@"%@",Hmodel.selectedModel.pair_id];
    
    NSString * amount = _tradeView.textField_Num.text;
    NSString * price = _tradeView.textField_Price.text;
    NSString * lever = [NSString stringWithFormat:@"%ld",(long)_tradeView.lever];
    NSDictionary * dic = @{
                           @"order_type":order_type,
                           @"pair_id":pair_id,
                           @"amount":amount,
                           @"price":price,
                           @"lever":lever,
                           @"source":@"2"
                           };
    
    NSString * URL = [NSString stringWithFormat:@"%@leverorder/generateOrder",DEFAULTSEVERBASEURL];
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.view];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]){
            [HUD showSuccessMessage:dic[@"msg"]];
            [weakSelf GetExLeverorderGetOrder];
        }else{
            [HUD showErrorMessage:dic[@"msg"]];
        }
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.view];
    }];
}


#pragma mark-打开菜单栏
-(void)openMenu{
    WS(weakSelf);
    MenuLeverageTradeView * popView = [MenuLeverageTradeView InitPopMenuLeverageTradeView];
    [popView show];
    _popView=popView;
    popView.block = ^(HomeBaseTabCellModel * _Nonnull model) {
        
        weakSelf.headerView.BTC.text=[NSString stringWithFormat:@"可用%@",model.base_symbol];
        weakSelf.headerView.USDT.text=[NSString stringWithFormat:@"可用%@",model.quote_symbol];

        
        HomeBaseModel * Hmodel =[HomeBaseModel sharedHomeBaseModel];
        if (model == Hmodel.selectedModel) {
        }else{
            [weakSelf.tradeView removeLeverageTradeButtonListDataSource];
            [LeverageTradeViewController dismissSocket:Hmodel.selectedModel];
            [LeverageTradeViewController openSocket:model];
            Hmodel.selectedModel = model;
            [weakSelf relayOutHeaderData];
            [weakSelf Http_leverassets_currency];
        }
        
        LeverageTradeModel * LTModel = [LeverageTradeModel sharedLeverageTradeModel];
        weakSelf.tradeView.dataSource=LTModel;
    };
}

#pragma mark-刷新WebSocket
-(void)relayOutWebSocket{
    SocketRocketUtility * SK = [SocketRocketUtility instance];
    [SK SRWebSocketClose];
    
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:WEBSOCKET_API_1];
}

-(void)relayOutPopView{
    if (_popView) {
        [_popView.slideView.home_USDTCell.tableView reloadData];
        [_popView.slideView.home_ETHCell.tableView reloadData];
        [_popView.slideView.home_BTCCell.tableView reloadData];
        [_popView.slideView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    }
}

#pragma mark-获取订单记录
-(void)GetExLeverorderGetOrder{
    
    NSString * token = [LoginModel GetValue:DL_token];
    if (token.length>0) {
    }else{
        self.tradeListRecordView.dataSource = nil;
        return;
    }
    
    HomeBaseModel * Hmodel =[HomeBaseModel sharedHomeBaseModel];

    NSString * URL = [NSString stringWithFormat:@"%@ex/leverorder/getOrder",DEFAULTSEVERBASEURL];
    
    NSString * pair_id = [NSString stringWithFormat:@"%@",Hmodel.selectedModel
                          .pair_id];
    
    NSDictionary * Dic = @{
                           @"page":@"1",
                           @"limit":@"20",
                           @"status":@"1",
                           @"pair_id":pair_id,
                           @"access_token":[LoginModel GetValue:DL_token]
                           };
    
    __weak __typeof(self)wself = self;
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:wself.view];
        NSDictionary * dic = responseObject;
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSDictionary * dicc = dic[@"data"];
            
            LeverageTradeModel * Model = [LeverageTradeModel sharedLeverageTradeModel];
            Model.orderModel = [LTOrderDataModel mj_objectWithKeyValues:dicc];
            wself.tradeListRecordView.dataSource = Model.orderModel;
            
        }
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:wself.view];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark-创建定时器
- (void)setUpTimer{
    [self stopTimer];
    WS(wself);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:wself selector:@selector(GetExLeverorderGetOrder) userInfo:nil repeats:YES];
    self.orderTimer = timer;
    [[NSRunLoop mainRunLoop ] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)stopTimer{
    //关闭定时器
    [self.orderTimer invalidate];
    self.orderTimer = nil;
}

- (void)dealloc{
    [self stopTimer];
}

#pragma mark-//取消订单
-(void)Http_leverorder_cancelorder:(NSString *)order_sn{
    NSString * URL = [NSString stringWithFormat:@"%@leverorder/cancelorder",DEFAULTSEVERBASEURL];
    NSDictionary * Dic = @{
                           @"order_sn":order_sn,
                           @"access_token":[LoginModel GetValue:DL_token]
                           };
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.view];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        if ([code isEqualToString:@"0"]) {
            [HUD showSuccessMessage:msg];
            [weakSelf GetExLeverorderGetOrder];
        }else{
            [HUD showErrorMessage:msg];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.view];
    }];
}


#pragma mark-//平仓
-(void)Http_leverposition_close:(NSString *)order_sn{
    NSString * URL = [NSString stringWithFormat:@"%@leverposition/close",DEFAULTSEVERBASEURL];
    NSDictionary * Dic = @{
                           @"order_sn":order_sn,
                           @"access_token":[LoginModel GetValue:DL_token]
                           };
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.view];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        if ([code isEqualToString:@"0"]) {
            [HUD showSuccessMessage:msg];
            [weakSelf GetExLeverorderGetOrder];
        }else{
            [HUD showErrorMessage:msg];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.view];
    }];
}




@end
